import * as React from 'react';
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, Checkbox, ConfigProvider, message } from 'antd';
import { ColumnProps } from 'antd/es/table';
import * as moment from 'moment';
import zhCN from 'antd/es/locale/zh_CN';
import './index.scss';

import { Link } from 'react-router-dom';
// 检索
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';

// 合同台账
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';
import { isHavePermission, isHavePathPermission } from '../../utils/utils';
import { dynamicsService } from '../../../../../services/services';
import { isArray } from 'lodash';
interface DataType {
  key: React.Key;
  number: string;
  name: string;
  handle: string;
  relative: string;
  dependent: string;
  time: string;
}

interface fromdata {
  field: string;
  text: string;
  errorMessage: string;
  required: boolean;
  type: string;
  value: any;
  options: any;
  theType: any;
  header: any;
  conditions: any;
}

const fromData: fromdata[] = [
  {
    field: 'date',
    text: '法务最后回答日',
    errorMessage: '请选择日期',
    required: false,
    type: 'date',
    value: null,
    options: [],
    theType: 'DateTime',
    header: 'LastAnswerTime',
    conditions: 'Geq'
  },
  {
    field: 'jobid',
    text: '语言',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: 'Language',
    conditions: 'Eq'
  },
  {
    field: 'username',
    text: '关键词1',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: 'Keyword1',
    conditions: 'Eq'
  },
  {
    // field: 'nature',
    field: 'customer',
    text: '问题',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: 'Problem',
    conditions: 'Eq'
  },
  {
    field: 'relyOn',
    text: '社内依赖者名',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: 'RelierName',
    conditions: 'Eq'
  },
  {
    field: 'nature',
    text: '合同性质',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: 'ContractNatureID',
    conditions: 'Eq'
  },
  {
    field: 'company',
    text: '所属公司',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: 'BelongsCompany',
    conditions: 'Eq'
  },
  {
    field: 'term',
    text: '合同期限',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: 'ContractDeadlineID',
    conditions: 'Eq'
  },
  {
    field: 'department',
    text: '所属部门',
    errorMessage: '请输入',
    required: false,
    type: 'char',
    value: undefined,
    options: [],
    theType: 'Text',
    header: 'BelongsDepartment',
    conditions: 'Eq'
  },
  {
    field: 'importance',
    text: '合同重要性',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: 'ContractSignificanceID',
    conditions: 'Eq'
  },
  {
    field: 'tobear',
    text: '审查担当',
    errorMessage: '请选择',
    required: false,
    type: 'multiSelect',
    value: undefined,
    options: [],
    theType: 'Text',
    header: 'ReviewOnID',
    conditions: 'Eq'
  },
  {
    field: 'modify',
    text: '合同修改性质',
    errorMessage: '请选择',
    required: false,
    type: 'multiSelect',
    value: undefined,
    options: [],
    theType: 'Text',
    header: 'ContactEditNature',
    conditions: 'Eq'
  },
  {
    field: 'number',
    text: '决裁编号',
    errorMessage: '请输入编号',
    required: false,
    type: 'char',
    value: '',
    options: [],
    theType: 'Text',
    header: 'RuleNumber',
    conditions: 'Eq'
  },
  {
    field: 'Lawyerreview',
    text: '律师审查',
    errorMessage: '请选择',
    required: false,
    type: 'select',
    value: undefined,
    options: [],
    theType: 'Number',
    header: 'LawyerReviewID',
    conditions: 'Eq'
  },
  {
    field: 'Legalacceptancedate',
    text: '法务受理日',
    errorMessage: '请选择日期',
    required: false,
    type: 'Picker',
    value: null,
    options: [],
    theType: 'DateTime',
    header: 'AcceptTime',
    conditions: 'Eq'
  }
];

const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
// 多选
const CheckboxGroup = Checkbox.Group;
// 选项所有数据
const plainOptions = [];
// 选中数组
const defaultCheckedList = [];
const columns: ColumnProps<DataType>[] = [
  {
    title: '编号',
    dataIndex: 'Title',
    key: 'Title',
    align: 'center',
    render(text, record: any) {
      if (record.difference == '合同') {
        return (
          <div>
            {
              <Link
                to={{
                  pathname:
                    record.VersionNum == 0 ? 'AddContractNo' : record.ContractStatus == '草稿' ? 'AddContractNo' : 'AddContractVersion',
                  state: { id: text }
                }}
              >
                {text}
              </Link>
            }
          </div>
        );
      } else if (record.difference == '规章') {
        return (
          <div>
            {
              <Link
                to={{
                  pathname: record.VersionNum == 0 ? 'Regulations' : record.RegulationsStatus == '草稿' ? 'Regulations' : 'RegulationsVersion',
                  state: { id: text }
                }}
              >
                {text}
              </Link>
            }
          </div>
        );
      } else if (record.difference == '案件') {
        return <div>{<Link to={{ pathname: 'CaseManagement', state: { id: text } }}>{text}</Link>}</div>;
      } else {
        return <div>{text}</div>;
      }
    }
  },
  {
    title: '相关内容',
    dataIndex: 'Name',
    key: 'Name',
    align: 'center'
  },
  // {
  //   title: '相关内容',
  //   dataIndex: 'handle',
  //   key: 'handle',
  //   align: 'center',
  //   render(text, recod: any) {
  //     
  //     return (
  //       <div>
  //         <span>
  //           依赖者名:{recod.RelierName};所属公司:{recod.BelongsCompany};
  //         </span>
  //       </div>
  //     );
  //   }
  // },
  {
    title: '分类',
    dataIndex: 'difference',
    key: 'difference',
    align: 'center',
    render(text, recod: any) {
      return (
        <div>
          <span>{recod.difference}</span>
        </div>
      )
    },
  },
  {
    title: '附件',
    dataIndex: 'file',
    key: 'file',
    align: 'center',
    render: relative => (
      <div>
        {relative &&
          relative.map(tag => {
            const dispUrl = ListGUID.DocumentLink;
            const splitName = tag.Name.split('.');
            console.log(splitName)
            return (
              <div key={tag}>
                {
                  splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank">{tag.Name}</a> : <a href={tag.Path} download={tag.Name} target="_blank">{tag.Name}</a>
                }
               
              </div>
            );
          })}
      </div>
    )
  }
];



const columnss: ColumnProps<DataType>[] = [
  {
    title: '搜索结果',
    dataIndex: 'file',
    key: 'file',
    align: 'left',
    render: (relative, item: any) => (
      <div>
        <div>
          {item.Title ? `编号：` : ''}<span dangerouslySetInnerHTML={{ __html: item.Title }}></span>
        </div>

        <div>
          {item.ContractName ? `合同编号：` : ''}<span dangerouslySetInnerHTML={{ __html: item.ContractName }}></span>
        </div>
        <div>
          {item.ContractSignificance ? `合同重要性：` : ''}<span dangerouslySetInnerHTML={{ __html: item.ContractSignificance }}></span>
        </div>
        <div>
          {item.ContractDeadline ? `合同期限：` : ''}<span dangerouslySetInnerHTML={{ __html: item.ContractDeadline }}></span>
        </div>
        <div>
          {item.ContractNature ? `合同性质：` : ''}<span dangerouslySetInnerHTML={{ __html: item.ContractNature }}></span>
        </div>

        <div>
          {item.Our ? `我方：` : ''}<span dangerouslySetInnerHTML={{ __html: item.Our }}></span>
        </div>

        <div>
          {item.Counterparty ? `相对方：` : ''}<span dangerouslySetInnerHTML={{ __html: item.Counterparty }}></span>
        </div>



        <div>
          {item.RegulationsName ? `规定名称：` : ''}<span dangerouslySetInnerHTML={{ __html: item.RegulationsName }}></span>
        </div>
        <div>
          {item.CaseSummary ? `案件概要：` : ''}<span dangerouslySetInnerHTML={{ __html: item.CaseSummary }}></span>
        </div>
        <div>
          {item.BelongsCompany ? `所属公司：` : ''}<span dangerouslySetInnerHTML={{ __html: item.BelongsCompany }}></span>
        </div>
        <div>
          {item.secrecy ? `保密程度：` : ''}<span dangerouslySetInnerHTML={{ __html: item.secrecy }}></span>
        </div>
        <div>
          {item.expire_date ? `到期时间：` : ''}<span dangerouslySetInnerHTML={{ __html: item.expire_date }}></span>
        </div>
        <div>
          {item.company_name ? `对方公司名称：` : ''}<span dangerouslySetInnerHTML={{ __html: item.company_name }}></span>
        </div>


        {relative &&
          relative.map(tag => {
            console.log(tag)
            const dispUrl = ListGUID.DocumentLink;
            const splitName = tag.name.split('.');
            return (
              <div>
                <div key={tag} style={{ display: 'flex', alignItems: 'center' }}>
                  <img src={tag.img} style={{ width: '20px', height: '20px' }} />
                  {/* <span style={{ fontSize: '16px', color: '#03A5D5', marginLeft: '5px' }}>{tag.name}</span> */}
                  {
                    
                    <div key={tag}>
                        {
                          splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} dangerouslySetInnerHTML={{ __html: tag.name }} target="_blank"></a> : <a href={tag.path} dangerouslySetInnerHTML={{ __html: tag.name }} download={tag.Name} target="_blank"></a>
                        }
                       
                      </div>
                  }
                  {/* <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank" dangerouslySetInnerHTML={{ __html: tag.name }}></a> */}
                </div>
                <div>
                  <p dangerouslySetInnerHTML={{ __html: tag.summary }}></p>
                </div>

                {/* <div>
                  <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank" dangerouslySetInnerHTML={{ __html: tag.url }}></a>
                </div> */}
              </div>
            );
          })}
      </div>
    )
  }
];

const data: DataType[] = [
  {
    key: '1',
    number: 'S s 20200202-01',
    name: '合同1',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
    dependent: '张丽  [S sW]',
    time: '2022-01-01  12:2:01'
  },
  {
    key: '2',
    number: 'B s 20200202-01',
    name: '合同2',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
    dependent: '张丽  [S sW]',
    time: '2022-01-01  12:2:01'
  },
  {
    key: '3',
    number: 'M s 20200202-01',
    name: '合同3',
    handle: '2022-01-01 ~ 2022-02-02',
    relative: '上海南洋万邦',
    dependent: '张丽  [S sW]',
    time: '2022-01-01  12:2:01'
  }
];
export default class SearchFile extends React.Component {
  constructor(props: any) {
    super(props);
  }

  list = ['测试数据', '测试数据1'];
  state = {
    pager: {
      current: 1,
      size: 10
    },
    time1: 0,
    time2: 0,
    time3: 0,
    time4: 0,
    time5: 0,
    time6: 0,
    time7: 0,
    cumulative: [],
    isTrue: false,
    checkedList: defaultCheckedList,
    // 多选初始选中状态
    indeterminate: false,
    // 是否全选状态
    checkAll: false,
    AccordinTotal: [],
    loading: false,
    inSearchOf: false,
    //表单数据对象
    local: zhCN, // 总数据数
    totalnum: 0,
    //表单数据对象
    data: [],
    multiSelect: [],
    form: {
      multiSelect: [],
      // 合同名称
      theContract: ''
    }
  };
  handleClick = value => {
    
  };
  onSelectChange = value => {
    
  };
  // 多选触发
  onChange = checkedValues => {
    
    this.setState({
      multiSelect: checkedValues
    });
  };
  onChange1 = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
      checkAll: checkedList.length === plainOptions.length
    });
  };

  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission();
    this.getTest(); // 测试代码，调试API使用
  }

  // 输入框改变赋值
  change(e, key) {
    
    this.setState({
      form: {
        ...this.state.form,
        [key]: e.target.value
      }
    });
  }
  // 获取指定字符前后
  getCaption = (obj, state) => {
    var index = obj.lastIndexOf("\.");
    if (state == 0) {
      obj = obj.substring(0, index);
    } else {
      obj = obj.substring(index + 1, obj.length);
    }
    return obj;
  }
  // 全选按钮触发
  onCheckAllChange = e => {
    this.setState({
      checkedList: e.target.checked ? plainOptions : [],
      indeterminate: false,
      checkAll: e.target.checked
    });
  };
  // 检索按钮触发
  theDraft = async () => {
    // let allFile = dynamicsService.getAllFileQuery({search: this.state.form.theContract})
    
    // 至少选择一个检索条件
    if (this.state.checkedList.length == 0) {
      message.warning('请选择检索范围');
      return;
    }
    // 至少选择一个关键字
    let conditions = [];
    

    if (this.state.inSearchOf) {
      message.warning('检索中');
      return
    }

    // 停止关闭所有定时器
    clearInterval(this.state.time1)
    clearInterval(this.state.time2)
    clearInterval(this.state.time3)
    clearInterval(this.state.time4)
    clearInterval(this.state.time5)


    this.state.cumulative = []

    conditions = this.state.form.theContract ? this.state.form.theContract.split(/\s+/) : []

    
    this.setState({
      loading: true,
      inSearchOf: true,
      cumulative: [],
      // pager: {
      //   current: 1,
      //   size: 10
      // },
    });

    // 选中检索范围
    // for (let i = 0; i < this.state.checkedList.length; i++) {
    //   // this.retrieve(this.state.checkedList[i], conditions)

    //   if (this.state.checkedList[i] == '合同申请书文件') {
    //     // 合同申请书文件
    //     let resultSearch = await Api._searchAllFiles(['ContractPetition'], this.state.form.theContract);
    //     // this.matching(resultSearch,conditions)
    //     // 
    //     let Naturcontract = this.matching(resultSearch, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }
    //   if (this.state.checkedList[i] == '合同台账文件') {
    //     // 合同台账文件
    //     let ContractPetition = await Api._searchAllFiles(['Contract'], this.state.form.theContract);
    //     let Naturcontract = this.matching(ContractPetition, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }
    //   if (this.state.checkedList[i] == '规定申请书文件') {
    //     // 规定申请书文件
    //     let Regulations = await Api._searchAllFiles(['RegulationsPetition'], this.state.form.theContract);
    //     let Naturcontract = this.matching(Regulations, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }
    //   if (this.state.checkedList[i] == '规定台账文件') {
    //     // 规定台账文件
    //     let RegulationsPetition = await Api._searchAllFiles(['Regulations'], this.state.form.theContract);
    //     let Naturcontract = this.matching(RegulationsPetition, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }
    //   if (this.state.checkedList[i] == '案件文件') {
    //     // 案件文件
    //     let CaseManagement = await Api._searchAllFiles(['CaseManagement'], this.state.form.theContract);
    //     let Naturcontract = this.matching(CaseManagement, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }
    //   // 查询通用文档库  这个库没有表 只需要显示附件
    //   if (this.state.checkedList[i] == '其他') {
    //     // 其他
    //     let Other = await Api._searchAllFiles(['Other'], this.state.form.theContract);
    //     let Naturcontract = this.matching(Other, conditions)
    //     this.state.cumulative = this.state.cumulative.concat(Naturcontract);
    //   }


    // }
    let guidList = ['FullTextSearch'];
    if(this.state.checkedList.indexOf('合同申请书文件') !== -1) {
      guidList.push(ListGUID.Petition)
      guidList.push(ListGUID.ContractPetitionLib)
    }
    if(this.state.checkedList.indexOf('规定申请书文件') !== -1) {
      guidList.push(ListGUID.Petition)
      guidList.push(ListGUID.RegulationsPetitionLib)
    }
    if(this.state.checkedList.indexOf('合同台账文件') !== -1) {
      guidList.push(ListGUID.StandingBook)
      guidList.push(ListGUID.ContractLib)
    }
    if(this.state.checkedList.indexOf('规定台账文件') !== -1) {
      guidList.push(ListGUID.Regulations)
      guidList.push(ListGUID.RegulationsLib)
    }
    if(this.state.checkedList.indexOf('案件文件') !== -1) {
      guidList.push(ListGUID.CaseManagement)
      guidList.push(ListGUID.CaseLib)
    }
    if(this.state.checkedList.indexOf('其他') !== -1) {
      guidList.push(ListGUID.CommonLib)
    }
    try {
      let arr = await Api._getPaged3({ Guid: guidList, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: [], search: this.state.form.theContract})
      let newAr = this.matching(arr.data, conditions)
      let nowPager = this.state.pager
      nowPager.current += 1
      // this.state.isTrue = false
      this.setState({
        isTrue: false,
        loading: false,
        inSearchOf: false,
        data: [...this.state.data, ...newAr],
        totalnum: arr.Total,
        pager: {
          current: nowPager.current,
          size: 10
        }
      }, () => {
        
      });
    } catch (error) {
      this.setState({
        isTrue: false,
        loading: false,
        inSearchOf: false,
      })
    }
    
    

  };


  matching(resultSearch, conditions) {
    
    resultSearch.forEach(element => {
      // 解析富文本 给加上 style 高亮样式
      let arrAy = conditions
      // let summary = child.summary.replace('2022', '\/<span style="background: #ffff00;color: #000000;font-weight: 700;">2022</span>')
      for (let i = 0; i < arrAy.length; i++) {
        if (element.Title != null) {
          element.Title = element.Title.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.ContractName != null) {
          element.ContractName = element.ContractName.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.ContractSignificance != null) {
          element.ContractSignificance = element.ContractSignificance.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.ContractDeadline != null) {
          element.ContractDeadline = element.ContractDeadline.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.ContractNature != null) {
          element.ContractNature = element.ContractNature.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.RegulationsName != null) {
          element.RegulationsName = element.RegulationsName.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.CaseSummary != null) {
          element.CaseSummary = element.CaseSummary.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.BelongsCompany != null) {
          element.BelongsCompany = element.BelongsCompany.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.secrecy != null) {
          element.secrecy = element.secrecy.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.expire_date != null) {
          element.expire_date = moment(element.expire_date).format('YYYY-MM-DD')
          element.expire_date = element.expire_date.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.company_name != null) {
          element.company_name = element.company_name.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.Our != null) {
          element.Our = element.Our.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
        if (element.Counterparty != null) {
          element.Counterparty = element.Counterparty.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
        }
      }

      // 
      
      if (element.FileObj) {
        element.FileObj = isArray(element.FileObj) ? element.FileObj : [element.FileObj]
        let file = []
        element.FileObj.forEach(child => {
          

          var name = child.Filename;
          // 解析富文本 给加上 style 高亮样式
          let arrAy = conditions
          // let summary = child.summary.replace('2022', '\/<span style="background: #ffff00;color: #000000;font-weight: 700;">2022</span>')
          let summary = child.HitHighlightedSummary || ''
          let UniqueId = child.UniqueId
          let url = child.Path
          
          if(arrAy && arrAy.length > 0) {
            for (let i = 0; i < arrAy.length; i++) {
              if(summary) {
                summary = summary.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
              }
              url = url.replace(RegExp(`${arrAy[i]}`, "g"), `<span style="background: #ffff00;color: #000000;font-weight: 700;">${arrAy[i]}</span>`)
            }
          }
         

          
          // 判断是否为文件夹
          if (name.indexOf('.') > -1) {
            // 获取文件类型
            // var type = name.substring(name.lastIndexOf(".") + 1);
            // let nameThe = this.getCaption(name, 0)
            let nameThe = child.Filename
            // 获取完整加版本号的编号 - 后
            let type = this.getCaption(name, 1)
            
            
            let img = ''
            if (type == "csv" || type == "xls" || type == "xlsx") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/xlsx.svg"
            } else if (type == "docx" || type == "doc") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/docx.svg"
            } else if (type == "pptx") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/pptx.svg"
            } else if (type == "onetoc") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/onetoc.svg"
            } else if (type == "vsdx") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/vsdx.svg"
            } else if (type == "pdf") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/pdf.svg"
            } else if (type == "tif") {
              img = "https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/tif.svg"
            }
            // 文件
            let obj = {
              // 文件路径链接
              url: '',
              // 文件类型
              type: '',
              // 文件名称
              name: '',
              // 文件图片
              img: '',
              // 内容
              summary: '',
              // 访问跳转的id
              UniqueId: '',
              path: ''
            }
            //文件路径链接
            obj.url = url
            // 文件类型
            obj.type = type
            // 文件名称
            obj.name = nameThe
            // 文件图片
            obj.img = img
            // 内容
            obj.summary = summary
            // 访问跳转的id
            obj.UniqueId = UniqueId
            obj.path = child.Path
            file.push(obj)

            element.file = file
          }
          // 文件夹暂不处理
          //  else {
          //   // 文件夹
          //   let obj = {
          //     // 文件路径链接
          //     url: '',
          //     // 文件类型
          //     type: 'folder',
          //     // 文件名称
          //     name: '',
          //     // 文件夹图片
          //     img: 'https://res-1.cdn.office.net/files/fabric-cdn-prod_20220825.001/assets/item-types/20/folder.svg',
          //     // 内容
          //     summary: '',
          //     // 访问跳转的id
          //     UniqueId: ''
          //   }
          //   // 文件夹只需要文件路径
          //   obj.url = child.resource.webUrl
          //   obj.name = name
          //   file.push(obj)
          //   element.file = file
          // }

        });
      } else {
        element.file = []
      }
    });
    
    return resultSearch
  }
  run = () => {
    let dom = document.querySelector('.scrollName .ant-table-body');
    if(dom.scrollHeight - dom.clientHeight - dom.scrollTop < 2) {
      this.theDraft()
    }
  }

  public render(): React.ReactElement {
    return (
      <div className="box">
        <div className="box_content">
          <div className="box_top">
            <Row type="flex" justify="start" align="middle">
              <Col span={2}>
                <div>关键字:</div>
              </Col>
              <Col span={18}>
                <Input
                allowClear
                  placeholder="多个关键字请用空格分隔"
                  value={this.state.form.theContract}
                  onChange={event => {
                    this.change(event, 'theContract');
                  }}
                />
              </Col>
              <Col span={4}>
                {true ? (
                  <Button type="primary" className="Button_3" onClick={() => this.setState({pager: {current: 1, size: 10}, data: []}, () => this.theDraft())}>
                    检索
                  </Button>
                ) : null}
              </Col>
            </Row>
            <div className="placeholder"></div>
            <Row type="flex" justify="start" align="middle">
              <Col span={22}>
                <Form.Item label="检索范围">
                  <CheckboxGroup options={plainOptions} value={this.state.checkedList} onChange={this.onChange1} />
                </Form.Item>
              </Col>
            </Row>
          </div>
          <div className="placeholder"></div>
          <div className="box_toble">
            <ConfigProvider locale={this.state.local}>
              {
                this.state.isTrue ? <Table
                columns={this.state.isTrue ? columns : columnss}
                dataSource={this.state.data}
                loading={this.state.loading}
                pagination={{
                  hideOnSinglePage: false,
                  onChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => {
                      this.getTest()
                    })
                  },
                  onShowSizeChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => this.getTest())
                  },
                  current: this.state.pager.current,
                  pageSize: this.state.pager.size,
                  total: this.state.totalnum,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultCurrent: 1,
                  showTotal: function (total) {
                    return `总共有 ${total} 条数据`;
                  }
                }}
              /> : <div onScrollCapture={() => this.run()}><Table
              columns={columnss}
              className="scrollName"
              dataSource={this.state.data}
              loading={this.state.loading}
              scroll={{ y: 500 }}
              pagination={false}
              // pagination={{
              //   hideOnSinglePage: false,
              //   onChange: (page, pageSize?) => {
              //     this.setState({
              //       pager: {
              //         current: page,
              //         size: pageSize
              //       }
              //     }, () => {
              //       this.theDraft()
              //     })
              //   },
              //   onShowSizeChange: (page, pageSize?) => {
              //     this.setState({
              //       pager: {
              //         current: page,
              //         size: pageSize
              //       }
              //     }, () => this.theDraft())
              //   },
              //   current: this.state.pager.current,
              //   pageSize: this.state.pager.size,
              //   total: this.state.totalnum,
              //   showSizeChanger: true,
              //   showQuickJumper: true,
              //   defaultCurrent: 1,
              //   showTotal: function (total) {
              //     return `总共有 ${total} 条数据`;
              //   }
              // }}
            /></div>
              }
              {/* <Table
                columns={this.state.isTrue ? columns : columnss}
                dataSource={this.state.data}
                loading={this.state.loading}
                pagination={{
                  hideOnSinglePage: false,
                  onChange: (page, pageSize?) => {
                    this.setState({
                      pager: {
                        current: page,
                        size: pageSize
                      }
                    }, () => {
                      this.getTest()
                    })
                  },
                  current: this.state.pager.current,
                  pageSize: this.state.pager.size,
                  total: this.state.totalnum,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  defaultCurrent: 1,
                  showTotal: function (total) {
                    return `总共有 ${total} 条数据`;
                  }
                }}
              /> */}
            </ConfigProvider>
          </div>
        </div>
        {/* <button onClick={this.handleClick}>{children}</button> */}
      </div>
    );
  }

  //合同性质 合同期限 合同重要性 律师审查 审查担当  公司设置  问题 部门列表
  public async getTest() {
    let params = [];
    let guidList = [];
    // 判断是否为法务部
    let MinistryJustice = await Api._isLegalDepartment();
    // MinistryJustice = false
    // 清空选项数组
    plainOptions.length = 0;
    
    if (MinistryJustice) {
      plainOptions.push('合同申请书文件')
      plainOptions.push('合同台账文件')
      plainOptions.push('规定申请书文件')
      plainOptions.push('规定台账文件')
      plainOptions.push('案件文件')
      plainOptions.push('其他')
      guidList = [ListGUID.Petition, ListGUID.StandingBook, ListGUID.Regulations, ListGUID.CaseManagement, ListGUID.CommonLib, 'FullSearch']
      params = []
    } else {
      plainOptions.push('合同申请书文件')
      plainOptions.push('规定申请书文件')
      plainOptions.push('其他')
      guidList = [ListGUID.Petition, ListGUID.CommonLib, 'FullSearch']
      params = []
    }
    this.setState({
      checkedList: []
    })
    return
    // 单选赋值
    this.state.checkedList = plainOptions;
    this.setState({
      loading: true
    });

    // 合同表
    // let Naturcontract :any
    // if (MinistryJustice) {
    //   var param = {
    //     Guid: ListGUID.StandingBook,
    //     PageSize: this.state.pager.size,
    //     PageIndex: this.state.pager.current
    //   };
    //   Naturcontract = await Api._getPaged(param);
    // } else {
    //   Naturcontract = []
    // }

    // if(Naturcontract.data) {
    //   Naturcontract.data.forEach(async element => {
    //     element.difference = '合同';
    //   });
  
    // }
    
    // Naturcontract.forEach(async element => {
    //   element.difference = '合同';
    //   if (element.FileAddress != null) {
    //     let file = await Api.getFiles(ListGUID.Petition + '/' + element.FileAddress);
    //     element.file = file;
    //   } else {
    //     element.file = [];
    //   }
    //   // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
    //   element.RegulationsName = element.ContractName;
    //   return;
    // });

    // fl 库
    // var FL = {
    //   Guid: ListGUID.Petition,
    //   PageSize: this.state.pager.size,
    //   PageIndex: this.state.pager.current
    // };
    // let flTheContract = await Api._getPaged(FL);

    // 
    // flTheContract.data.forEach(async element => {
    //   element.difference = 'FL';
    // });

    // flTheContract.forEach(async element => {
    //   element.difference = 'FL';
    //   if (element.SRUrls != null) {
    //     let index = element.SRUrls.lastIndexOf('/');
    //     element.SRUrls = element.SRUrls.substring(0, index);
    //     

    //     let file = await Api.getFiles(element.SRUrls);
    //     element.file = file;
    //   } else {
    //     let file = [];
    //     element.file = file;
    //   }

    //   // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
    //   if (element.apply_user_nm != null) {
    //     element.RegulationsName = element.filename;
    //   } else {
    //     element.RegulationsName = '';
    //   }
    //   return;
    // });

    // 规章制度同表
    // let Naturcontract1 :any
    // if (MinistryJustice) {
    //   var param1 = {
    //     Guid: ListGUID.Regulations, //案件表数据
    //     PageSize: this.state.pager.size,
    //     PageIndex: this.state.pager.current
    //   };
    //   Naturcontract1 = await Api._getPaged(param1);
    // } else {
    //   Naturcontract1 = []
    // }
    // if(Naturcontract1.data) {
    //   Naturcontract1.data.forEach(async element => {
    //     element.difference = '规章';
    //   });
    // }
    
    // Naturcontract1.forEach(async element => {
    //   element.difference = '规章';
    //   if (element.FileAddress != null) {
    //     let file = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + element.FileAddress);
    //     element.file = file;
    //   } else {
    //     element.file = [];
    //   }
    // });

    // 案件
    // let Naturcontract2 :any
    // if (MinistryJustice) {
    //   var theCase = {
    //     Guid: ListGUID.CaseManagement, //案件表数据
    //     PageSize: this.state.pager.size,
    //     PageIndex: this.state.pager.current
    //   };
    //   Naturcontract2 = await Api._getPaged(theCase);
    // } else {
    //   Naturcontract2 = []
    // }
    // if(Naturcontract2.data) {
    //   Naturcontract2.data.forEach(async element => {
    //     element.difference = '案件';
    //   });
    // }
    

    // Naturcontract2.forEach(async element => {
    //   element.difference = '案件';
    //   if (element.FileAddress != null) {
    //     let file = await Api.getFiles(ListGUID.CaseLibRelativeUrl + '/' + element.FileAddress);
    //     element.file = file;
    //   } else {
    //     element.file = [];
    //   }

    //   element.RegulationsName = element.CaseName;
    //   return;
    // });

    // 通用文档库
    // let Naturcontract3 = await Api._getPaged({
    //   Guid: ListGUID.CommonLib,
    //   PageSize: this.state.pager.size,
    //   PageIndex: this.state.pager.current
    // });
    // // filter: "FSObjType eq 0 and substringof('同导',FileLeafRef)" });
    // 
    // if(Naturcontract3.data) {
    //   Naturcontract3.data.forEach(async element => {
    //     element.difference = '通用';
    //   });
  
    // }
    
    // Naturcontract3.forEach(async element => {
    //   let arr = [];
    //   arr.push(element.File);
    //   element.Title = '';
    //   element.RegulationsName = '';
    //   element.handle = '';
    //   element.file = arr;
    //   return;
    // });

    // let arr = Naturcontract.data.concat(Naturcontract1.data);
    // arr = arr.concat(Naturcontract2.data);
    // // fl
    // arr = arr.concat(flTheContract.data);
    // arr = arr.concat(Naturcontract3.data);
    // 
    let arr = await Api._getPaged({ Guid: guidList, PageSize: this.state.pager.size, PageIndex: this.state.pager.current, FilterL: params})
    // let arr = [...Naturcontract.data || [], ...Naturcontract2.data || [], ...Naturcontract3.data || [], ...flTheContract.data || []]

    let TotalAll = arr.Total || 0



    // let size = 0
    // // 追加附件的数据数量

    // let num = 10

    // if (arr.length < 10) {
    //   num = arr.length
    // }

    // let array = []
    // for (let i = 0; i < num; i++) {
    //   
    //   array.push(arr[size])
    //   size++
    // }
    for(let i = 0; i < arr.data.length; i ++) {
      if (arr.data[i].difference == '合同') {
        if (arr.data[i].FileAddress != null) {
          
          let file = await Api.getFiles(ListGUID.ContractLibRelativeUrl + '/' + arr.data[i].FileAddress);
          arr.data[i].file = file;
        } else {
          arr.data[i].file = [];
        }
        // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
        arr.data[i].RegulationsName = arr.data[i].ContractName;


      } else if (arr.data[i].difference == '申请书') {

        if (arr.data[i].FileAddress != null) {
          
          let file = [];
          // ContractPetitionLibRelativeUrl RegulationsPetitionLibRelativeUrl

          if(arr.data[i].FileAddress.includes('ContractPetitionLib')) {
            let index = arr.data[i].FileAddress.indexOf("/")
            arr.data[i].FileAddress = arr.data[i].FileAddress.substring(index);
            file = await Api.getFiles(ListGUID.ContractPetitionLibRelativeUrl + '/' + arr.data[i].FileAddress + '/');
          } else {
            let index = arr.data[i].FileAddress.indexOf("/")
            arr.data[i].FileAddress = arr.data[i].FileAddress.substring(index);
            file = await Api.getFiles(ListGUID.RegulationsPetitionLibRelativeUrl + '/' + arr.data[i].FileAddress + '/');
          }
          


          // let index = arr.data[i].SRUrls.lastIndexOf('/');
          // arr.data[i].SRUrls = arr.data[i].SRUrls.substring(0, index);
          // 
          
          // let file = await Api.getFiles(arr.data[i].SRUrls);
          arr.data[i].file = file;
        } else {
          let file = [];
          arr.data[i].file = file;
        }

        // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
        if (arr.data[i].apply_user_nm != null) {
          arr.data[i].RegulationsName = arr.data[i].filename;
        } else {
          arr.data[i].RegulationsName = '';
        }

      } else if (arr.data[i].difference == '规章') {

        if (arr.data[i].FileAddress != null) {
          let file = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + arr.data[i].FileAddress);
          arr.data[i].file = file;
        } else {
          arr.data[i].file = [];
        }

      } else if (arr.data[i].difference == '案件') {

        if (arr.data[i].FileAddress != null) {
          let file = await Api.getFiles(ListGUID.CaseLibRelativeUrl + '/' + arr.data[i].FileAddress);
          arr.data[i].file = file;
        } else {
          arr.data[i].file = [];
        }

        arr.data[i].RegulationsName = arr.data[i].CaseName;

      } else if (arr.data[i].difference == '通用') {

        let arr1 = [];
        arr.push(arr.data[i].File);
        arr.data[i].Title = '';
        arr.data[i].RegulationsName = '';
        arr.data[i].handle = '';
        arr.data[i].file = arr1;
        return;

      }
    }

    this.state.time5 = setTimeout(() => {
      this.setState({
        data: arr.data,
        totalnum: TotalAll,
        loading: false,
        inSearchOf: false,
      });
    }, 500);
  }

  public async theQuery(params, Guid, name) {
    
    

    let camlQuery = {
      ViewXml: ''
    };

    //不排序
    let demo = Api.buildCamlXml(params);

    camlQuery.ViewXml = demo;

    

    let Naturcontract1 = await Api.GetListItemsByCAMLQuery(Guid, camlQuery);

    
    if (name == '合同申请书' || name == '规定申请书文件') {
      Naturcontract1.forEach(async element => {
        element.difference = 'FL';

        if (element.SRUrls != null) {
          let index = element.SRUrls.lastIndexOf('/');
          element.SRUrls = element.SRUrls.substring(0, index);
          

          let file = await Api.getFiles(element.SRUrls);
          element.file = file;
        } else {
          let file = [];
          element.file = file;
        }

        // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
        // element.RegulationsName = element.apply_user_nm
        if (element.apply_user_nm != null) {
          element.RegulationsName = element.filename;
        } else {
          element.RegulationsName = '';
        }
        // return
      });

      this.state.time4 = setTimeout(() => {
        this.state.AccordinTotal = this.state.AccordinTotal.concat(Naturcontract1);
        let arr = this.state.AccordinTotal;
        this.setState({
          data: arr,
          totalnum: arr.length,
          loading: false,
          inSearchOf: false,
        });
      }, 1000);
      
    }

    if (name == '合同台账文件') {
      Naturcontract1.forEach(async element => {
        // 
        element.difference = '合同';
        if (element.FileAddress != null) {
          let file = await Api.getFiles(ListGUID.Petition + '/' + element.FileAddress);
          element.file = file;
        } else {
          element.file = [];
        }

        // let file = await Api.getFiles(ListGUID.Petition + '/' + element.FileAddress);
        // element.file = file
        // 规章制度 跟 案件的合同名称是 RegulationsName 需要三个一致
        element.RegulationsName = element.ContractName;
        // return
      });

      this.state.time3 = setTimeout(() => {
        this.state.AccordinTotal = this.state.AccordinTotal.concat(Naturcontract1);
        let arr = this.state.AccordinTotal;
        this.setState({
          data: arr,
          totalnum: arr.length,
          loading: false,
          inSearchOf: false,
        });
      }, 1000);
    }

    if (name == '规定台账文件') {
      Naturcontract1.forEach(async element => {
        element.difference = '规章';
        if (element.FileAddress != null) {
          let file = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + element.FileAddress);
          element.file = file;
        } else {
          element.file = [];
        }
        // return
      });
      

      this.state.time2 = setTimeout(() => {
        this.state.AccordinTotal = this.state.AccordinTotal.concat(Naturcontract1);
        let arr = this.state.AccordinTotal;
        this.setState({
          data: arr,
          totalnum: arr.length,
          loading: false,
          inSearchOf: false,
        });
      }, 1000);
    }

    if (name == '案件文件') {
      Naturcontract1.forEach(async element => {
        element.difference = '案件';
        if (element.FileAddress != null) {
          let file = await Api.getFiles(ListGUID.CaseLibRelativeUrl + '/' + element.FileAddress);
          element.file = file;
        } else {
          element.file = [];
        }

        // let file = await Api.getFiles(ListGUID.CaseLibRelativeUrl + '/' + element.FileAddress);
        // element.file = file
        element.RegulationsName = element.CaseName;
        // return
      });

      this.state.time1 = setTimeout(() => {
        this.state.AccordinTotal = this.state.AccordinTotal.concat(Naturcontract1);
        let arr = this.state.AccordinTotal;
        
        this.setState({
          data: arr,
          totalnum: arr.length,
          loading: false,
          inSearchOf: false,
        });
      }, 1000);
    }
  }



}
